import { Space, Button, DatePicker, message, Modal, Divider, Select } from 'antd';
import { ExclamationCircleOutlined, PaperClipOutlined } from '@ant-design/icons';

import React, { useState, useRef } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { paramToStringRemovePage } from '@/utils/utils';
import { queryLog ,removeLog,batchRemoveLog} from '@/services/log';
import DetailForm from './components/DetailForm';
const { confirm } = Modal;
import styles from '/src/global.less';


//删除单个
const handleRemove = async (fields: any) => {
  const hide = message.loading('正在删除');
  try {
    await removeLog({ id: fields.logId });
    hide();
    message.success('删除成功，正在刷新！');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};


const Log: React.FC = () => {

  const columns: ProColumns[] = [
    {
      title: '操作时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        return (
          <DatePicker />
        )
      },
    },
    {
      title: '操作人',
      dataIndex: 'userName',

    }, {
      title: 'IP地址',
      dataIndex: 'machineIp',

    }, {
      title: '模块名称',
      dataIndex: 'moduleName',

    },
    {
      title: '操作',
      dataIndex: 'operationName',

    },

    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => (
        <>
          <a
            key="select"
            onClick={async () => {
              handleUpdateModalVisible(true);
              setFormValues(record);
            }}
          >
            详情
          </a>
          <Divider type="vertical" />
          <a onClick={() => {
            confirm({
              title: '您确定要删除吗?',
              icon: <ExclamationCircleOutlined />,
              async onOk() {
                await handleRemove(record);
                ref.current?.reload();
              },
              onCancel() {
                console.log('Cancel');
              },
            });
          }}
          >
            删除
          </a>
      </>
      )
    },
  ];


  const ToExport = async () => {
    const hide = message.loading('导出中');
    try {
      window.location.href="/api/log/exportExcel?"+paramToStringRemovePage(searchDate);
      return true;
    } catch (error) {
      hide();
      message.error('导出失败请重试！');
      return false;
    }
  };

  const [searchDate, setSearchDate] = useState({});
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
 
  const [formValues, setFormValues] = useState({});
  const ref = useRef<ActionType>();

  const [selectedRowKeys,setSelectedRowKeys] = useState<number[]>([]);
  const onSelectChange = async (sKeys ) => {
    setSelectedRowKeys(sKeys);

  };
  
//批量删除
const batchRemove = async () => {
  const hide = message.loading('正在删除');
  try {
    await batchRemoveLog({ ids: selectedRowKeys.join(',')});
    setSelectedRowKeys([]);
    hide();
    message.success('删除成功，正在刷新！');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};

  return (
    <>
      <ProTable
        actionRef={ref}
      
        columns={columns}
        options={false}
        dateFormatter="string"
        search={{
          span: 6,
          labelWidth: 'auto',
        }}
        rowSelection={{selectedRowKeys,onChange: onSelectChange}}
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        tableAlertOptionRender={() => {
          return (
            <Space size={16}>
              <a  onClick={() => {
              confirm({
                title: '您确定要批量删除吗?',
                icon: <ExclamationCircleOutlined />,
                async onOk() {
                  await batchRemove();
                  ref.current?.reload();
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }} >批量删除</a>
              {/* <a>导出数据</a> */}
            </Space>
          );
        }}
        request={(params) =>{setSearchDate(params); return  queryLog(params)} }
        rowKey="logId"
        pagination={{
          showQuickJumper: true,
        }}
        headerTitle=""
        toolBarRender={() => [
          <Button className={styles.exportBtn}   onClick={()=>ToExport()} >
              <PaperClipOutlined /> 导出
          </Button>
        ]}
      />
      {formValues && Object.keys(formValues).length ? (
        <DetailForm
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
        />
      ) : null}
    </>
  );
};

export default Log;